﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Request.Divided;
using WCS.Infrastructure.Dto.Request.Log;
using WCS.Infrastructure.Dto.Request.Payment;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Service.Instance;
using WCS.Service.Interface;

namespace WCS.Api.Admin.Controllers
{
    /// <summary>
    /// 分账管理
    /// </summary>
    public class DividedController : BaseController
    {
        private readonly IConfiguration _configuration;
        private readonly IDividedService _dividedService;
        private readonly IPaymentService _paymentService;
        private readonly ILogService _logService;


        public DividedController(IConfiguration configuration, IDividedService dividedService, IPaymentService paymentService,
            ILogService logService,IUserService userService) : base(userService)
        {
            _configuration = configuration;
            _dividedService = dividedService;
            _paymentService = paymentService;
            _logService = logService;
        }

        /// <summary>
        /// 在分账协议里面批量设置收款码（该协议下的收款码列表与目标集合对齐）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "在分账协议里面批量设置收款码", Group = "分账模块")]
        public async Task<IActionResult> SetDividedAgreementPaymentCodes(SetDividedAgreementPaymentCodesRequestDto dto)
        {
            var result = await _dividedService.SetDividedAgreementPaymentCodesAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 新增分账协议【AgreementName，MerchantId，DividedCycle，StartTime,EndTime,ParentAgreementId】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增分账协议", Group = "分账模块")]
        public async Task<IActionResult> AddDividedAgreement(DividedAgreementRequestDto dto)
        {
            var result = await _dividedService.AddDividedAgreementAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 获取分账协议列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key">根据分账协议名称</param>
        /// <param name="merchantId">商户ID</param>
        /// <param name="enableStatus">启用状态</param>
        /// <param name="activationStatus">激活状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedAgreementList(int page = 1, int limit = 10, string? key = "", string? merchantId = "", int enableStatus = -1, int activationStatus = -1)
        {
            var result = await _dividedService.GetDividedAgreementListAsync(new DividedAgreementRequestDto
            {
                Page = page,
                Limit = limit,
                Key = key,
                MerchantId = merchantId,
                EnableStatus = enableStatus,
                ActivationStatus = activationStatus
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取单个分账协议详细信息
        /// </summary>
        /// <param name="id">分账协议ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedAgreement(string id)
        {
            var result = await _dividedService.GetDividedAgreementAsync(id);
            return Ok(result);
        }

        /// <summary>
        /// 编辑分账协议【Id，AgreementName，DividedCycle，StartTime，EndTime，EnableStatus】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "编辑分账协议", Group = "分账模块")]
        public async Task<IActionResult> UpdateDividedAgreement(DividedAgreementRequestDto dto)
        {
            var result = await _dividedService.UpdateDividedAgreementAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 禁用/启用分账协议
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "禁用/启用分账协议", Group = "分账模块")]
        public async Task<IActionResult> BanDividedAgreementAsync(BanDividedAgreementRequestDto dto)
        {
            var result = await _dividedService.BanDividedAgreementAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 删除分账协议（归档删除）【Id】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "删除分账协议", Group = "分账模块")]
        public async Task<IActionResult> DeleteDividedAgreement(DividedAgreementRequestDto dto)
        {
            var result = await _dividedService.DeleteDividedAgreementAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 查询与（当前或指定）用户相关的分账协议列表（标注参与者/创作者）
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <param name="userId">目标用户ID（可选，默认取当前登录用户）</param>
        /// <param name="merchantId">商户ID（可选）</param>
        /// <param name="includeParticipation">是否包含作为参与者的协议</param>
        /// <param name="includeOwned">是否包含作为创作者的协议</param>
        /// <param name="enableStatus">启用状态过滤（-1 不过滤）</param>
        /// <param name="activationStatus">激活状态过滤（-1 不过滤）</param>
        /// <param name="onlySubAgreements">仅返回子协议</param>
        /// <param name="onlyMyDetailsWithoutSubAgreement">默认false,为true时仅返回“当前用户在协议中的明细未绑定子协议”的参与项</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserRelatedDividedAgreements(
            int page = 1,
            int limit = 10,
            string? userId = "",
            string? merchantId = "",
            bool includeParticipation = true,
            bool includeOwned = true,
            int enableStatus = -1,
            int activationStatus = -1,
            bool onlySubAgreements = false,
            bool onlyMyDetailsWithoutSubAgreement = false)
        {
            var result = await _dividedService.GetUserRelatedDividedAgreementsAsync(
                new WCS.Infrastructure.Dto.Response.Payment.DividedAgreementUserQueryDto
                {
                    Page = page,
                    Limit = limit,
                    UserId = userId,
                    MerchantId = merchantId,
                    IncludeParticipation = includeParticipation,
                    IncludeOwned = includeOwned,
                    EnableStatus = enableStatus,
                    ActivationStatus = activationStatus,
                    OnlySubAgreements = onlySubAgreements,
                    OnlyMyDetailsWithoutSubAgreement = onlyMyDetailsWithoutSubAgreement,
                });

            return Ok(result);
        }

        /// <summary>
        /// 获取分账协议详情列表
        /// </summary>
        /// <param name="dividedAgreementId">分账协议ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedAgreementDetailList(string dividedAgreementId)
        {
            var result = await _dividedService.GetDividedAgreementDetailListAsync(dividedAgreementId);
            return Ok(result);
        }


        /// <summary>
        /// 新增分账协议详情【DividedAgreementId，Ratio，UserId，UserRoleId】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增分账协议详情", Group = "分账模块")]
        public async Task<IActionResult> AddDividedAgreementDetail(DividedAgreementDetailRequestDto dto)
        {
            var result = await _dividedService.AddDividedAgreementDetailAsync(dto);
            return Ok(result);
        }


        /// <summary>
        /// 删除分账协议详情【ids】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "删除分账协议详情", Group = "分账模块")]
        public async Task<IActionResult> DeleteDividedAgreementDetail(DividedAgreementDetailRequestDto dto)
        {
            var result = await _dividedService.DeleteDividedAgreementDetailAsync(dto);
            return Ok(result);
        }


        /// <summary>
        /// 编辑分账协议详情【Id，Ratio，UserId】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "编辑分成协议详情", Group = "分账模块")]
        public async Task<IActionResult> UpdateDividedAgreementDetail(DividedAgreementDetailRequestDto dto)
        {
            var result = await _dividedService.UpdateDividedAgreementDetailAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 编辑分账协议详情(批量)【List(Id，Ratio，UserId)】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "编辑分成协议详情(批量)", Group = "分账模块")]
        public async Task<IActionResult> UpdateDividedAgreementDetails(List<DividedAgreementDetailRequestDto> dto)
        {
            var result = await _dividedService.UpdateDividedAgreementDetailsAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 确认分账协议详情
        /// </summary>
        /// <param name="id">分账协议详情ID</param>
        /// <param name="phone">分账人手机号</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ConfirmDividedAgreementDetail(string? id = "", string? phone = "")
        {
            var result = await _dividedService.ConfirmDividedAgreementDetailAsync(new DividedAgreementDetailRequestDto
            {
                Id = id,
                UserPhone = phone
            });
            return Ok(result);
        }

        /// <summary>
        /// 新增分账（惠旺店手动分账）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [ActionLog(Action = "新增分账（惠旺店手动分账）", Group = "分账模块")]
        public async Task<IActionResult> AddDividedRecord()
        {
            var result = await _dividedService.AddDividedRecordAsync();
            return Ok(result);
        }

        /// <summary>
        /// 分账结算（惠旺店手动分账结算）
        /// </summary>
        /// <param name="dividedTime"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [ActionLog(Action = "分账结算（惠旺店手动分账结算）", Group = "分账模块")]
        public async Task<IActionResult> UpdateDividedRecord(DateTime dividedTime)
        {
            var result = await _dividedService.UpdateDividedRecordAsync(dividedTime);
            return Ok(result);
        }

        /// <summary>
        /// 手动执行定时结算，分账，分账结算任务
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [ActionLog(Action = "手动执行定时结算，分账，分账结算任务", Group = "支付模块")]
        public async Task ExecuteSettlementTask(DateTime dateTime)
        {
            // 1) 结算
            try
            {
                var result = await _paymentService.AddSettlementRecordAsync(dateTime);
                if (result.code == ApiCode.ok)
                {
                    await _logService.AddActionLogAsync(new ActionLogRequestDto
                    {
                        ApiUrl = "AtRegularTime.Settlement",
                        Type = "定时任务",
                        Action = "结算",
                        Params = $"{dateTime}",
                        Result = 0,
                        ResultMessage = "定时结算任务执行成功",
                        UserId = ""
                    });
                }
                else if (result.code == ApiCode.fail)
                {
                    await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                    {
                        Api = "AtRegularTime.Settlement",
                        Message = $"定时结算任务执行失败: {result.message}",
                        Params = $"{dateTime}",
                        UserId = ""
                    });
                    return;
                }
                else
                {
                    await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                    {
                        Api = "AtRegularTime.Settlement",
                        Message = "定时结算任务超时",
                        Params = $"{dateTime}",
                        UserId = ""
                    });
                    return;
                }
            }
            catch (Exception ex)
            {
                await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                {
                    Api = "AtRegularTime.Settlement",
                    Message = $"执行结算任务时发生异常：{ex.Message}",
                    Params = $"{dateTime}",
                    UserId = ""
                });
                return;
            }

            // 2) 分账
            try
            {
                var result1 = await _dividedService.AddDividedRecordAsync();
                if (result1.code == ApiCode.ok)
                {
                    await _logService.AddActionLogAsync(new ActionLogRequestDto
                    {
                        ApiUrl = "AtRegularTime.Divided",
                        Type = "定时任务",
                        Action = "分账",
                        Params = $"{dateTime}",
                        Result = 0,
                        ResultMessage = "定时分账任务执行成功",
                        UserId = ""
                    });
                }
                else if (result1.code == ApiCode.fail)
                {

                    await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                    {
                        Api = "AtRegularTime.Divided",
                        Message = $"定时分账任务执行失败: {result1.message}",
                        Params = $"{dateTime}",
                        UserId = ""
                    });
                    return;
                }
                else
                {
                    await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                    {
                        Api = "AtRegularTime.Divided",
                        Message = "定时分账任务超时",
                        Params = $"{dateTime}",
                        UserId = ""
                    });
                    return;
                }
            }
            catch (Exception ex)
            {

                await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                {
                    Api = "AtRegularTime.Divided",
                    Message = $"执行分账任务时发生异常：{ex.Message}",
                    Params = $"{dateTime}",
                    UserId = ""
                });
                return;
            }

            // 3) 分账结算
            try
            {
                var result2 = await _dividedService.UpdateDividedRecordAsync(dateTime);
                if (result2.code == ApiCode.ok)
                {
                    await _logService.AddActionLogAsync(new ActionLogRequestDto
                    {
                        ApiUrl = "AtRegularTime.DividedSettlement",
                        Type = "定时任务",
                        Action = "分账结算",
                        Params = $"{dateTime}",
                        Result = 0,
                        ResultMessage = "定时分账结算任务执行成功",
                        UserId = ""
                    });
                }
                else if (result2.code == ApiCode.fail)
                {
                    await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                    {
                        Api = "AtRegularTime.DividedSettlement",
                        Message = $"定时分账结算任务执行失败: {result2.message}",
                        Params = $"{dateTime}",
                        UserId = ""
                    });
                    return;
                }
                else
                {
                    await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                    {
                        Api = "AtRegularTime.DividedSettlement",
                        Message = "定时分账结算任务超时",
                        Params = $"{dateTime}",
                        UserId = ""
                    });

                }
            }
            catch (Exception ex)
            {
                await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                {
                    Api = "AtRegularTime.DividedSettlement",
                    Message = $"执行分账结算任务时发生异常：{ex.Message}",
                    Params = $"{dateTime}",
                    UserId = ""
                });
                return;
            }
        }

        

        /// <summary>
        /// 获取分账记录报表
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="merchantId">商户ID传值时返回商户的分账记录报表</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedRecordReport(DateTime beginTime, DateTime endTime, string? merchantId = "")
        {
            var result = await _dividedService.GetDividedRecordReportAsync(new DividedRecordQueryRequestDto
            {
                BeginTime = beginTime,
                EndTime = endTime,
                MerchantId = merchantId

            });
            return Ok(result);
        }


        /// <summary>
        /// 获取用户分账记录列表
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedRecordList(DateTime beginTime, DateTime endTime, int page = 1, int limit = 10)
        {
            var result = await _dividedService.GetDividedRecordListAsync(new DividedRecordQueryRequestDto
            {
                Page = page,
                Limit = limit,
                BeginTime = beginTime,
                EndTime = endTime
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取商户分账记录列表
        /// </summary>
        /// <param name="dividedDate">分账日期(年/月/日)</param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="merchantId">商户ID</param>
        /// <param name="dividedAgreementId">分账协议ID</param>
        /// <param name="codeId">收款码ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMerchantDividedRecordList(DateTime dividedDate, int page = 1, int limit = 10, string? merchantId = "", string? dividedAgreementId = "", string? codeId = "")
        {
            var result = await _dividedService.GetMerchantDividedRecordListAsync(new DividedRecordQueryRequestDto
            {
                Page = page,
                Limit = limit,
                DividedDate = dividedDate,
                MerchantId = merchantId,
                DividedAgreementId = dividedAgreementId,
                CodeId = codeId
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取用户分账记录详情树状图
        /// </summary>
        /// <param name="dividedRecordId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedRecordTreeForUser(string dividedRecordId)
        {
            var result = await _dividedService.GetDividedRecordTreeForUserAsync(dividedRecordId);
            return Ok(result);
        }

        /// <summary>
        /// 获取完整分账树状图
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <param name="dividedRecordId">订单ID</param>
        [HttpGet]
        public async Task<IActionResult> GetDividedRecordFullTreeByOrderId(string? orderId, string? dividedRecordId)
        {
            var result = await _dividedService.GetDividedRecordFullTreeByOrderIdAsync(orderId, dividedRecordId);
            return Ok(result);
        }

        /// <summary>
        /// 获取分账记录根层详情
        /// </summary>
        /// <param name="dividedRecordId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedRecordRootLayer(string dividedRecordId)
        {
            var result = await _dividedService.GetDividedRecordRootLayerAsync(dividedRecordId);
            return Ok(result);
        }

        /// <summary>
        /// 获取分账记录详情列表
        /// </summary>
        /// <param name="dividedRecordId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDividedRecordDetailList(string dividedRecordId)
        {
            var result = await _dividedService.GetDividedRecordDetailListAsync(dividedRecordId);
            return Ok(result);
        }
    }
}
